'''
Created on Jan 29, 2011

@author: pdellera
'''
import os
import glob
import re
from datetime import date
import mc
from xml.dom.minidom import parseString

class DailyColbertBase :
    logLevel = 2
    version = "0.79"

    def __init__(self):
        self.config = mc.GetApp().GetLocalConfig()

        if self.config.GetValue("app.exiting") == "true":
            return

        try:
            # Set the version on any page that loads
            # ToDo: read read the version from descriptor.xml
            mc.GetActiveWindow().GetLabel(1013).SetLabel(self.version)
        except:
            pass

        # If this is the first time the app is being run, lets set some default options.
        if not self.config.GetValue("app.firstrun"):
            self.config.SetValue("app.firstrun", "true")


    """
    log - logging function mainly for debugging
    """
    def log(self, message):
        if self.logLevel == 3:
            mc.ShowDialogNotification(message)

        if self.logLevel >= 2:
            mc.LogDebug(">>> DailyColbert: " + message)

        if self.logLevel == 1:
            mc.LogInfo(">>> DailyColbert: " + message)
            #print ">>> DailyColbert: " + message

class DailyColbertMain(DailyColbertBase):
    nameparser=re.compile('(.*?)[- _\.](\d\d\d\d[- /_\.]\d\d[- /_\.]\d\d)[- /_\.]?(.*)')
    """
    __init__ - Gather playlist destination and build menu
    """
    def __init__(self):
        #mc.GetApp().GetLocalConfig().Reset("playlist.url")
        DailyColbertBase.__init__(self)
        
    def BuildMenu(self):
        try:
            line=0
            mc.ShowDialogNotification( "Creating Main Menu (v%s)..." % self.version)
            self.log("CreateMainMenu %s..." % self.version)
            line = 10
            playlistUrl = self.config.GetValue("playlist.url")
            if len(playlistUrl) == 0:
                playlistUrl = "http://dellera12:8089/files"
            #self.log("playlist.url: %s" % playlistUrl)
            line = 20
            filelist = self.GetPlaylistFilenames(playlistUrl)
            line = 30
            filelist.sort(self.compare)
            dateHeader = date(1970, 1, 1)
            dynamicMenu = mc.ListItems()

            filenum = 0
            for pathname in filelist:
                line = 40
                filenum = filenum + 1
                pathname = pathname.rstrip()
                #self.log("#%d (%d): \"%s\"" % (filenum, len(pathname), pathname))
                #self.log("pathname len %d" % len(pathname))
                #self.log("pathname \"%s\"" % pathname)
                match=self.nameparser.match(pathname);
                if(match):
                    line = 50
                    showdate = match.group(2)
                    showdate=re.sub('[/\._ ]', '-', showdate)
                    arr = showdate.split('-')
                    if len(arr) == 3:
                        line = 60
                        d = date(int(arr[0]), int(arr[1]), int(arr[2]))
                        line = 61
                        if dateHeader != d :
                            line = 62
                            dateHeader = d
                            line = 63
                            item = mc.ListItem(mc.ListItem.MEDIA_UNKNOWN)
                            line = 64
                            item.SetPath(pathname)
                            line = 65
                            item.SetLabel(dateHeader.strftime("%a, %b %d, %Y"))
                            line = 66
                            #self.log(item.GetPath())
                            line = 67
                            dynamicMenu.append(item)
                    line = 70
                    arr = os.path.splitext(os.path.basename(pathname))[0].split('-')
                    if len(arr) == 2:
                        guest = arr[1]
                    else:
                        guest = "TBD"
                    if(arr[0][0] == '1'):
                        tvshow = "        DS:    %s" % guest
                    else:
                        tvshow = "        CR:    %s" % guest
                        
                    line = 80
                    item = mc.ListItem(mc.ListItem.MEDIA_UNKNOWN)
                    item.SetPath(pathname)
                    item.SetLabel(tvshow)
                    #self.log(item.GetPath())
                    dynamicMenu.append(item)
                else:
                    self.log("Could not parse name component: %s" % pathname)
                    break
            #self.log("Adding %i menu items." % len(dynamicMenu))
            mc.GetActiveWindow().GetList(100).SetItems(dynamicMenu)
        except Exception, e:
            self.log("(%i)Error %s" % (line, e))

    def getText(self, nodelist):
        rc = []
        for node in nodelist:
            if node.nodeType == node.TEXT_NODE:
                rc.append(node.data)
        return ''.join(rc)
    
    def handleFileDirectory(self, filedirectory):
        files = filedirectory.getElementsByTagName("file")
        filenames = self.handleFiles(files)
        return filenames
    
    def handleFiles(self, files):
        filenames = []
        for file in files:
            filename = self.getText(file.childNodes)
            #filenames.append(filename.encode('utf-8'))
            filenames.append(unicode(filename).encode('utf-8'))
        return filenames

    def GetPlaylistFilenames(self, playlistUrl):
        filenames = []
        try:
            http = mc.Http()
            data = http.Get(playlistUrl)
            dom = parseString(data)
            filenames = self.handleFileDirectory(dom)
        except Exception, e:
            self.log("Error %s" % (e))
        #self.log("Returning %i filenames." % len(filenames))
        return filenames

    def compare(self, a, b):
    #    return cmp(int(a), int(b)) # compare as integers
    
    #    a_path=os.path.dirname(a)
        a_filename=os.path.basename(a)
        a_nameparts=os.path.splitext(a_filename)
        a_basename=a_nameparts[0]
    #    a_extension=a_nameparts[1]
        a_IsDS = False
        if(a_basename[0] == '1'):
            a_IsDS = True
    
    #    b_path=os.path.dirname(b)
        b_filename=os.path.basename(b)
        b_nameparts=os.path.splitext(b_filename)
        b_basename=b_nameparts[0]
    #    b_extension=b_nameparts[1]
        b_IsDS = False
        if(b_basename[0] == '1'):
            b_IsDS = True
        
        a_match=self.nameparser.match(a_basename);
        b_match=self.nameparser.match(b_basename);
    
        if(a_match):
            (a_raw_showname, a_raw_showdate)=a_match.group(1, 2)
            a_parsed_showname=re.sub('[\._-]', ' ', a_raw_showname)
            a_parsed_showdate=re.sub('[/\._ ]', '-', a_raw_showdate)
        else:
            self.log("Could not parse A name component: %s" %  a_basename)
            return 0
    
        if(b_match):
            (b_raw_showname, b_raw_showdate)=b_match.group(1, 2)
            b_parsed_showname=re.sub('[\._-]', ' ', b_raw_showname)
            b_parsed_showdate=re.sub('[/\._ ]', '-', b_raw_showdate)
        else:
            self.log("Could not parse B name component: %s" % b_basename)
            return 0
    
    #    if(verbose):
    #        print "A Name:", a_parsed_showname
    #        print "A Date:", a_parsed_showdate
    #        print "B Name:", b_parsed_showname
    #        print "B Date:", b_parsed_showdate
            
        ret = cmp(a_parsed_showdate, b_parsed_showdate)
        if( ret == 0):
            # If one is a Daily show and the other is not, position
            # the Daily Show to the top
            if(a_IsDS==True and b_IsDS==False):
                ret = -1
            elif(b_IsDS==True and a_IsDS==False):
                ret = 1
        
        return ret

class DailyColbertSettings(DailyColbertBase):
    def __init__(self):
        DailyColbertBase.__init__(self)
        self.config = mc.GetApp().GetLocalConfig()

        if self.config.GetValue("app.exiting") == "true":
            return

        line=202
        try:
            line=204
            playlistUrl = self.config.GetValue("playlist.url")
            if len(playlistUrl) == 0:
                line=207
                playlistUrl = "http://MyServer:8089/files"
            playlistUrl = mc.ShowDialogKeyboard("Enter playlist WEB URL:", playlistUrl, False)
            #self.log("Got playlist.url as %s" % playlistUrl)
            if len(playlistUrl) > 0:
                line=207
                self.config.SetValue("playlist.url", playlistUrl) 
            #self.log("Returning playlist.url as %s" % self.config.GetValue("playlist.url"))
        except Exception, e:
            self.log("(%i)Error %s" % (line, e))

